/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


var cellsClickableCalled = false;
var turn;
var fromCell, toCell;
var game;
var gameTableName;
var sessionPieceColor;
var gameFinished;
var intervalID;
var initialTimerValue;
var currentTimerValue;
var gameAlreadyStarted = false;
var timer;



//window.onbeforeunload = function(){
//    alert("unload");
//   ajaxRequest(null, "?req=deleteTable&tableName="+gameTableName);
//}

            
function init(tableName, sessionColor){
    gameTableName = tableName;
    sessionPieceColor = sessionColor;
    
    if (sessionColor == "WHITE"){
         
                
        var table = document.getElementById("chess_board");
        for (var i = 7 ; i >= 0 ; i--){
            var tr = document.createElement("tr");
                    
            for (var j = 0 ; j < 8 ; j++){
                var td = document.createElement("td");
                td.setAttribute("id", i+""+j);
                var a = document.createElement("a");
                a.setAttribute("href", "javascript:void(0)");
                td.appendChild(a);
                tr.appendChild(td);
            }
            table.appendChild(tr);
        }
    }
     
    else if (sessionColor == "BLACK"){
         
                
        table = document.getElementById("chess_board");
        for ( i = 0 ; i <8 ; i++){
            tr = document.createElement("tr");
                    
            for ( j = 7 ; j >= 0 ; j--){
                td = document.createElement("td");
                td.setAttribute("id", i+""+j);
                a = document.createElement("a");
                a.setAttribute("href", "javascript:void(0)");
                td.appendChild(a);
                tr.appendChild(td);
            }
            table.appendChild(tr);
        }
    }
                
    ajaxRequest(updateGameCallback, "?req=updateGame&gameTableName="+gameTableName);
    interval = setInterval(function(){
        ajaxRequest(updateGameCallback, "?req=updateGame&gameTableName="+gameTableName);
    },4500);
            
            
    for ( i = 0 ; i < 8 ; i++)
        for ( j = 0 ; j < 8 ; j++){
            cell = document.getElementById(i+""+j);
            cell.childNodes[0].onclick = function(){
                cellClicked(this.parentNode.id);
            };
        }
}
            
            
            
function updateGameCallback(data){
    
    if (data!=null){
        
        if (data!="null\n"){
            game = JSON.parse(data);
    

            setTimersIfNecessary();  
   
            turn = game.turn;
            gameFinished = game.gameFinished;
            if (gameFinished == true){
                alert("Game is finished the winner is: "+game.winner.name );
                clearInterval(intervalID);
                window.location.href = "home.html";

            }
                     
            drawPieces();
            
            
        
        
            //update game players information------------------------------
        
            labelPlayer1Turn = document.getElementById("player1Turn");
            labelPlayer2Turn = document.getElementById("player2Turn");

        
            labelPlayer1Turn.innerHTML = "";
            labelPlayer2Turn.innerHTML="";
    
            if (turn=="WHITE")
                labelPlayer1Turn.innerHTML =  "&#10004;"
        
    
            else
                labelPlayer2Turn.innerHTML =  "&#10004;"
        
        
        }
    }
        
        
}


function drawPieces(){
    var cell ;
    
    for (var i = 0 ; i < 8 ; i++)
        for (var j = 0 ; j < 8 ; j++){
            piece = game.board.field[i][j].piece;
            cell = document.getElementById(i+""+j);
           
            if (piece != undefined){
                if (piece.color == "WHITE"){
                            
                    if (piece.type == "PIECE")
                        cell.childNodes[0].innerHTML = "&#9678;";
                               
                    else if (piece.type == "KING")
                        cell.childNodes[0].innerHTML = "&#10032;";
                            
                            
                    cell.setAttribute("class","WHITE");
                            
                }
                else if (piece.color == "BLACK"){
                    if (piece.type == "PIECE")
                        cell.childNodes[0].innerHTML = "&#9673;";
                    else if (piece.type == "KING")
                        cell.childNodes[0].innerHTML = "&#10026;";
                        
                    cell.setAttribute("class","BLACK");
                
            
                }
                    
            }
            else 
                cell.childNodes[0].innerHTML = "";
            

        }
    

    //-------------------------setting cursor--------------
                
    for ( i = 0 ; i < 8 ; i++)
        for ( j = 0 ; j < 8 ; j++){
            piece = game.board.field[i][j].piece;
            cell = document.getElementById(i+""+j);
            if (piece != undefined){
                if (piece.color != sessionPieceColor){
                    cell.childNodes[0].setAttribute("style", "cursor:default");
                }
                else{
                    cell.childNodes[0].setAttribute("style", "cursor: hand");
                }
                
            }
        
        }
}
            
    
function cellClicked(cellId){
    if (gameFinished == false){
        if (game.player2 != undefined){
            //"#3090C7" 
            var cell = document.getElementById(cellId);
            var piece = game.board.field[cellId.charAt(0)][cellId.charAt(1)].piece;
                    
            if (game.turn == sessionPieceColor ){
                if (fromCell == undefined){
                    if ( piece!=undefined)
                        if( game.turn == piece.color){
                            fromCell = cellId;
                            cell.style.background="#3090C7";
   
                        }
                }
                else if(fromCell != undefined && toCell == undefined){
                    if (piece == undefined){
                        toCell = cellId;
                        cell.style.background="#3090C7";
                               
                        ajaxRequest(updateGameCallback, "?req=makeMove&from="+fromCell+"&to="+toCell+"&gameTableName=" +gameTableName);
                        cell.style.background="";
                        document.getElementById(fromCell).style.background="";
                                
                        fromCell = undefined;
                        toCell = undefined;
                                
               
                    }
                    else if (cellId == fromCell){
                        fromCell = undefined;
                        cell.style.background="";
                    }
                                
                    else if (game.turn == piece.color){
                                    
                        document.getElementById(fromCell).style.background="";
                        fromCell = cellId;
                        cell.style.background="#3090C7";
                    }
                }
            }
        }
    }
    
}
            
            

function setCountdown(timerValue, elementId){
    currentTimerValue = timerValue;
    timer = setInterval(function (){
        if (currentTimerValue <= 0){
            clearInterval(timer);
            return;
        }
        currentTimerValue--;
        label = document.getElementById(elementId);
        label.innerHTML=currentTimerValue;
            
    }, 1000);
}

function setTimersIfNecessary(){
    if (!gameFinished){
        if (game.player2!=null){
            if (!gameAlreadyStarted){   
                ajaxRequest(setTimerValue, "?req=getRemainingTime&gameTableName="+gameTableName);
                gameAlreadyStarted = true;

                return;
            }
        
            if (turn!=game.turn){
                document.getElementById("player1Time").innerHTML="";
                document.getElementById("player2Time").innerHTML="";
                
                clearInterval(timer);
                ajaxRequest(setTimerValue, "?req=getRemainingTime&gameTableName="+gameTableName);
            }
        }
    }
        
    
    
    
    
}
function setTimerValue(data){
    var timerValue = Math.floor( data/1000);
    var elementId;
    if (game.turn == "WHITE"){
        elementId = "player1Time";
    }
    else
        elementId = "player2Time";
    setCountdown(timerValue, elementId);

}
    
